<template>
  <div style="padding: 0 17px">
    <Breadcrumb/>
    <div style="display: flex;margin-top: 20px">
      <!--<el-button icon="edit" type="primary" style="margin-right: 15px" @click="editItem">新增-->
      <!--</el-button>-->
<!--      <el-button icon="Delete" type="danger" style="margin-right: 15px" @click="deleteSelect">删除所选-->
<!--      </el-button>-->
      <span style="min-width: 200px;margin-right: 15px">
          <OrganizationTree
                  @change="load"
                  v-model="selectedOrganizationId"
                  @tree-select-changed="treeSelectChanged"
          />
      </span>
      <el-input v-model="search" placeholder="查岗人姓名"
                style="width: 200px;height: 33px;margin-right: 15px;font-size: 13px;" clearable></el-input>
      <el-button icon="Search" type="primary" style="color: #fff;font-size: 12px;background-color: #1890ff;" @click="load">搜索
      </el-button>
      <el-button type="success" style="" @click="importData">导入</el-button>
      <el-button type="success" style="" @click="exportData">导出</el-button>
    </div>
    <div>
      <el-table :data="tableData" :row-style="{ height: '77px' }" border style="width: calc(100vw - 240px);margin-top: 20px;height: 70vh;color: #909399;font-size: 15px;" @selection-change="handleSelectionChange">
        <!--<el-table-column-->
            <!--type="selection"-->
            <!--width="55">-->
        <!--</el-table-column>-->
        <el-table-column prop="id" label="ID" width="100"/>
        <el-table-column prop="userName" label="查岗人姓名" width="180"/>
        <el-table-column prop="startTime" label="发起时间" width="auto"/>
        <el-table-column prop="endTime" label="结束时间" width="auto"/>
        <el-table-column prop="state" label="查岗状态" width="auto"/>
        <el-table-column prop="ip" label="ip地址" width="auto"/>
        <el-table-column prop="result" label="查岗结果" width="auto"/>
        <el-table-column align="center" label="操作" fixed="right" width="180">
          <template v-slot="scope">
            <el-button type="primary" size="small" icon="edit" @click="editItem(scope.row)">编辑</el-button>
<!--            <el-button type="danger" size="small" icon="Delete" @click="deleteItem(scope.row.id)">删除</el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :background="true"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <el-dialog :close-on-click-modal="false" title="查岗记录操作" v-model="operationItemDialog" :show-close="false" width="700">
    <el-form :inline="true" :model="form" ref="form" :rules="rules">
      <!--<el-form-item label="单位名称" prop="clientId">-->
        <!--<el-select style="width: 190px" v-model="form.clientId" filterable placeholder="选择单位名称">-->
          <!--<el-option-->
                  <!--v-for="item in clientOptions"-->
                  <!--:key="item.id"-->
                  <!--:label="item.name"-->
                  <!--:value="item.id">-->
          <!--</el-option>-->
        <!--</el-select>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="查岗人姓名" prop="userName">-->
        <!--<el-input placeholder="请输入查岗人姓名" v-model="form.userName" autocomplete="off"></el-input>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="发起时间" prop="startTime">-->
        <!--<el-date-picker-->
                <!--v-model="form.startTime"-->
                <!--value-format="YYYY-MM-DD HH:mm:ss"-->
                <!--type="datetime"-->
                <!--placeholder="选择日期时间">-->
        <!--</el-date-picker>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="结束时间" prop="endTime">-->
        <!--<el-date-picker-->
                <!--v-model="form.endTime"-->
                <!--value-format="YYYY-MM-DD HH:mm:ss"-->
                <!--type="datetime"-->
                <!--placeholder="选择日期时间">-->
        <!--</el-date-picker>-->
      <!--</el-form-item>-->
      <!--<el-form-item label="查岗状态" prop="state">-->
        <!--<el-input placeholder="请输入查岗状态" v-model="form.state" autocomplete="off"></el-input>-->
      <!--</el-form-item>-->
      <el-form-item label="查岗结果" prop="result">
        <el-input placeholder="请输入查岗结果" v-model="form.result" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="reset('form')">取 消</el-button>
      <el-button type="primary" @click="submitForm('form')">确 定</el-button>
    </div>
  </el-dialog>
  <el-dialog title="导入" v-model="dialogImportVisible" width="520px">
    <el-form label-position="right" label-width="100px">
      <el-form-item label="模板下载:" padding-top:10px>
        <el-button type="primary" size="small" style="" @click="exportTemplate">查岗记录</el-button>
      </el-form-item>
      <el-form-item label="文件" padding-top:-20px>
        <el-upload :headers="headers"
                           :multiple="false"
                   :on-success="onUploadSuccess"
                   :on-error="onUploadError"
                   :action="serverIp+'/record-check/importData'"
                   class="upload-demo">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传xlsx文件</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogImportVisible = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from "@/utils/request.js";
import Breadcrumb from "@/components/Breadcrumb.vue";
import OrganizationTree from "@/components/OrganizationTree.vue";
import {serverIp} from "../../../public/static/config"
export default {
  name: "CheckRecord",
  components: {Breadcrumb, OrganizationTree},
  data() {
    return{
      serverIp,
                headers: {
                    token:  JSON.parse(localStorage.getItem('user')).token,
                },
      dialogImportVisible: false,
      selectedOrganizationId: JSON.parse(localStorage.getItem("user")).organization,
      currentData:{},
      clientOptions:[],
      selectOptionName:"",
      operationItemDialog: false,
      form:{},
      tableData:[],
      searchData:[],
      search:"",
      currentPage: 1,
      pageSize: 10,
      total: 10,
      // 选择框
      multipleSelection: [],
      rules: {
        userName: [
          {required: true, message: '请输入查岗人姓名', trigger: 'blur'},
        ],
        clientId: [
          {required: true, message: '请输入单位名称', trigger: 'blur'},
        ],
        stateTime: [
          {required: true, message: '请选择发起时间', trigger: 'blur'},
        ],
        endTime: [
          {required: true, message: '请选择结束时间', trigger: 'blur'},
        ],
        state: [
          {required: true, message: '请输入查岗状态', trigger: 'blur'},
        ],
        result: [
          {required: true, message: '请选择查岗结果', trigger: 'blur'},
        ],

      },
    }
  },
  created() {
    this.load()
    // this.getClientOptions()
  },
  methods: {
    importData() {
      this.dialogImportVisible = true;
    },
    onUploadSuccess() {
      this.$message.success('上传成功');
      this.dialogImportVisible = false;
      location.reload();
    },
    onUploadError(){
      this.$message.error('上传失败');
    },
    // 模板下载
    exportTemplate() {
      window.location.href = '../xlsx/recordCheck.xlsx'
    },
    exportData() {
      let level = JSON.parse(localStorage.getItem("user")).level
      let id = JSON.parse(localStorage.getItem("user")).id
      window.open(serverIp + '/record-check/export?keyWord=' + this.search +
              "&userId="+id + "&level="+ level + "&organizationId="+ this.selectedOrganizationId);
    },
    getClientOptions(){
      let level = JSON.parse(localStorage.getItem("user")).level
      let organizationId = JSON.parse(localStorage.getItem("user")).organization
      let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
      let clientIds;
      if (isAllClient === "1") {
        clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
      } else {
        clientIds = [];
      }
      request.get("/client/listbyName?name="+this.selectOptionName+"&organizationId="+organizationId+"&level="+level+"&isAllClient="+isAllClient+"&clientIds="+clientIds).then(res=>{
        this.clientOptions=res.data
      })
    },
    treeSelectChanged(data) {
      this.currentData = data
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection)
    },
    handleSizeChange(pageSize) {   // 改变当前每页的个数触发
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {  // 改变当前页码触发
      this.currentPage = pageNum
      this.load()
    },
    // 编辑
    editItem(scope) {
      Object.assign(this.form,scope)
      this.operationItemDialog = true
    },
    // 编辑、新增确定按钮
    submitForm(val) {
      this.$refs[val].validate((valid) => {
        if (valid) {
          request.post("/record-check/edit", this.form).then(res => {
            if (res.code === '200') {
              this.$message({
                message: "成功",
                type: "success"
              })
              this.load()
              this.reset("form")
            } else {
              this.$message.error("操作失败" + res.msg)
            }
          })
        }
      })
    },
    reset(val) {
      this.operationItemDialog = false;
      this.form = {};
      this.$refs[val].clearValidate();
    },
    /*
    // 删除单个
    deleteItem(scope){
      this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.get("/record-check/delete/"+scope).then(res=>{
          if (res.code==='200'){
            this.$message.success("成功")
            this.load()
          }else {
            this.$message.error("删除失败，"+res.msg)
          }
        })
      });
    },
    deleteSelect(){
      this.$confirm('是否确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (this.multipleSelection.length===0){
          this.$message.error("未选择数据")
          return
        }
        const idList=[];
        this.multipleSelection.forEach(row => {
          idList.push(row.id)
        });
        request.post("/record-check/deleteByIdList",idList).then(res=>{
          if (res.code==='200'){
            if (res.data){
              this.$message.success("成功")
            }else {
              this.$message.error("删除失败")
            }
            this.load()
          }else {
            this.$message.error("删除失败，"+res.msg)
          }
        })
      });
    },
     */
    // 搜索及初始化
    load(){
      let id = JSON.parse(localStorage.getItem("user")).id
      let level = JSON.parse(localStorage.getItem("user")).level
      request.get("/record-check/page?pageNum=" + this.currentPage + "&pageSize=" + this.pageSize + "&keyWord="+this.search+
              "&userId="+ id + "&level="+ level + "&organizationId="+ this.selectedOrganizationId).then(res => {
        if (res.code === '200') {
          for (let key in res.data) {
            if (key === "record") {
              this.tableData = res.data[key];
            } else if (key === "total") {
              this.total = res.data[key];
            }
          }
        } else {
          this.$message.error("错误"+res.msg)
        }
      })
    }
  }
}
</script>

<style scoped>
:deep(.el-table th .cell)  {
  font-weight: 700
}
:deep(.el-form-item__label) {
  font-size: 14px;
  font-weight: 700
}
.input-size {
  font-size: 14px;
}
</style>
